package com.atomlab.daycheck.ui.database;

import static com.atomlab.daycheck.model.ObjectTypeInfoHelper.getObjectTypeInfo;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.atomlab.daycheck.R;
import com.atomlab.daycheck.databinding.ActivityDatabaseBinding;
import com.atomlab.daycheck.model.Student;
import com.atomlab.daycheck.model.StudentAdapter;
import com.atomlab.daycheck.model.personInfo;
import com.bin.david.form.core.SmartTable;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.huawei.agconnect.AGConnectInstance;
import com.huawei.agconnect.auth.AGConnectAuth;
import com.huawei.agconnect.cloud.database.AGConnectCloudDB;
import com.huawei.agconnect.cloud.database.CloudDBZone;
import com.huawei.agconnect.cloud.database.CloudDBZoneConfig;
import com.huawei.agconnect.cloud.database.CloudDBZoneObjectList;
import com.huawei.agconnect.cloud.database.CloudDBZoneQuery;
import com.huawei.agconnect.cloud.database.CloudDBZoneSnapshot;
import com.huawei.agconnect.cloud.database.exceptions.AGConnectCloudDBException;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;

import java.util.ArrayList;
import java.util.List;

public class DatabaseActivity extends AppCompatActivity {

    private ActivityDatabaseBinding binding;
    private static String TAG = "DatabaseActivity:";
    //初始化数据库
    AGConnectCloudDB mCloudDB;
    //初始化数据库配置
    CloudDBZoneConfig mConfig;
    //初始化存储区
    CloudDBZone mCloudDBZone;

    //初始化表格
    private SmartTable<Student> table;
    //云端数据对象List
    private static List<personInfo> personInfoList = new ArrayList<>();

    private UiCallBack mUiCallBack = UiCallBack.DEFAULT;
    private String displayName = "";
    private FloatingActionButton fab;
    private int listSize = 0;
    private ActivityResultLauncher<Intent> intentActivityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityDatabaseBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        Toolbar toolbar = binding.toolbar;
        setSupportActionBar(toolbar);
        CollapsingToolbarLayout toolBarLayout = binding.toolbarLayout;
        toolBarLayout.setTitle("每日健康打卡");

        table = (SmartTable<Student>) findViewById(R.id.table);
        initView();

        fab = binding.fab;
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final AlertDialog.Builder normalDialog =  new AlertDialog.Builder(DatabaseActivity.this);
                normalDialog.setIcon(R.mipmap.ic_tab_me_off);
                normalDialog.setTitle("提示");
                normalDialog.setMessage("是否退出登录?"  );
                normalDialog.setPositiveButton("确定",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                        AGConnectAuth.getInstance().signOut();
                        Log.i(TAG, "onClick: log out successfully");
                        finish();
                    }
                });
                normalDialog.setNegativeButton("取消",  new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
                // 显示
                normalDialog.show();
            }
        });

        Button cb = binding.cb;
        cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gotoCheckActivity(null,listSize);
            }
        });

        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                //此处是跳转的result回调方法
                if (result.getResultCode() == Activity.RESULT_OK) {
                    initView();
                } else {

                }
            }
        });
    }

    private void initView() {
        //获取用户名（手机号）
        displayName = getIntent().getStringExtra("DisplayName");
        //初始化云数据库

        AGConnectCloudDB.initialize(getApplicationContext());
        AGConnectInstance instance = AGConnectInstance.getInstance();
        mCloudDB = AGConnectCloudDB.getInstance(instance, AGConnectAuth.getInstance(instance));
        Log.i(TAG,"The cloudDB is" + mCloudDB);
        try {
            mCloudDB.createObjectType(getObjectTypeInfo());
            mConfig = new CloudDBZoneConfig("personInfoZone",
                    CloudDBZoneConfig.CloudDBZoneSyncProperty.CLOUDDBZONE_CLOUD_CACHE,
                    CloudDBZoneConfig.CloudDBZoneAccessProperty.CLOUDDBZONE_PUBLIC);
            mConfig.setPersistenceEnabled(true);
            Task<CloudDBZone> openDBZoneTask = mCloudDB.openCloudDBZone2(mConfig, true);
            openDBZoneTask.addOnSuccessListener(new OnSuccessListener<CloudDBZone>() {
                @Override
                public void onSuccess(CloudDBZone cloudDBZone) {
                    Log.i("open clouddbzone", "open cloudDBZone success");
                    mCloudDBZone = cloudDBZone;
                    //开始绑定数据
                    bindData();
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(Exception e) {
                    Log.w("open clouddbzone", "open cloudDBZone failed for " + e.getMessage());
                }
            });
        } catch (AGConnectCloudDBException e) {
            Toast.makeText(DatabaseActivity.this, "initialize CloudDB failed" + e, Toast.LENGTH_LONG).show();
        }
    }
    private void bindData() {
        CloudDBZoneQuery<personInfo> query = CloudDBZoneQuery.where(personInfo.class);
        queryPersonInfo(query);
    }

    private List<personInfo> queryPersonInfo(CloudDBZoneQuery<personInfo> query) {
        if (mCloudDBZone == null) {
            Log.w(TAG, "CloudDBZone is null, try re-open it");
            return null;
        }

        Task<CloudDBZoneSnapshot<personInfo>> queryTask = mCloudDBZone.executeQuery(query,
                CloudDBZoneQuery.CloudDBZoneQueryPolicy.POLICY_QUERY_FROM_CLOUD_ONLY);
        //List<personInfo> tmpInfoList = new ArrayList<>();
        queryTask.addOnSuccessListener(new OnSuccessListener<CloudDBZoneSnapshot<personInfo>>() {
            @Override
            public void onSuccess(CloudDBZoneSnapshot<personInfo> snapshot) {
                try {
                    personInfoList = processQueryResult(snapshot);
                } catch (AGConnectCloudDBException e) {
                    Log.e(TAG, "onfailed: "+e.getErrMsg() );
                }
                Log.i(TAG, "onSuccess: query result success");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                mUiCallBack.updateUiOnError("Query failed");
                Log.i(TAG, "onSuccess: query result failed");
            }
        });
        return personInfoList;
    }

    private List<personInfo> processQueryResult(CloudDBZoneSnapshot<personInfo> snapshot) throws AGConnectCloudDBException {
        CloudDBZoneObjectList<personInfo> personInfoCursor = snapshot.getSnapshotObjects();
        List<personInfo> infoList = new ArrayList<>();
        List<Student> list = new ArrayList<>();
        try {
            while (personInfoCursor.hasNext()) {
                personInfo info = personInfoCursor.next();
                infoList.add(info);
                list.add(new Student(info.getId(),info.getName(),info.getTemperature(),
                        info.getGreen()?"是":"否",info.getInoculation(),info.getPhone(),info.getAddress()));
//                list.add(new Student(2,"郭郭","13480026269","东莞市高埗镇",36.2f,true,3));
            }
            listSize = list.size();
        } catch (AGConnectCloudDBException e) {
            Log.w(TAG, "processQueryResult: " + e.getMessage());
        } finally {
            snapshot.release();
            mCloudDB.closeCloudDBZone(mCloudDBZone);
        }

        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,5);
        recyclerView.setLayoutManager(gridLayoutManager);

        StudentAdapter adapter = new StudentAdapter(list);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new StudentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Student student = list.get(position);
                gotoCheckActivity(student,0);

            }
        });

        table.clearFocus();
        table.setData(list);
//        table.getConfig().setContentStyle(new FontStyle(50, Color.BLUE));
        table.getConfig().setShowTableTitle(false);
        table.getConfig().setShowXSequence(false);
        table.getConfig().setShowYSequence(false);
        table.setScrollContainer(true);
        table.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), v.getTooltipText(), Toast.LENGTH_LONG).show();
            }
        });
        mUiCallBack.onAddOrQuery(infoList);
        return infoList;
    }

    private void gotoCheckActivity(Student student,int listSize)
    {
        Intent intent = new Intent();
        intent.setClass(DatabaseActivity.this, CheckActivity.class);
        intent.putExtra("student",student);
        intent.putExtra("id", listSize);
        intentActivityResultLauncher.launch(intent);
    }

    /**
     * Call back to update ui
     */
    public interface UiCallBack {
        UiCallBack DEFAULT = new UiCallBack() {
            @Override
            public void onAddOrQuery(List<personInfo> bookInfoList) {
                Log.i(TAG, "Using default onAddOrQuery");
            }

            @Override
            public void onSubscribe(List<personInfo> bookInfoList) {
                Log.i(TAG, "Using default onSubscribe");
            }

            @Override
            public void onDelete(List<personInfo> bookInfoList) {
                Log.i(TAG, "Using default onDelete");
            }

            @Override
            public void updateUiOnError(String errorMessage) {
                Log.i(TAG, "Using default updateUiOnError");
            }
        };

        void onAddOrQuery(List<personInfo> infoList);

        void onSubscribe(List<personInfo> infoList);

        void onDelete(List<personInfo> infoList);

        void updateUiOnError(String errorMessage);
    }
}